package controllers.caterinaController.controllers;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import controllers.Checks;
import controllers.dbWrapper.TransactionWrapper;
import person.Employee;
import transaction.Transaction;
import transaction.Transaction.Type;

public class TransactionManager {

	public static void payWages(Employee ... employee) throws Exception{
		TransactionWrapper.payWages(true);
	}
	
	
	
	public static Map<Integer, Map<String, Double>> getAllStats() throws Exception{
		ArrayList<Transaction> allTrans = TransactionWrapper.getAllTransaction(true);
		Map<Integer, Map<String, Double>> stats = new TreeMap<Integer, Map<String,Double>>(
				new Comparator<Integer>() {public int compare(Integer o1, Integer o2) {return -(o1-o2);}}
		);
		Map<String,Double>yearMap;
		for(Transaction tr:allTrans){
			if((yearMap=(HashMap<String, Double>) stats.get(tr.getDate().get(Calendar.YEAR)))==null){
				yearMap=new HashMap<String, Double>();
				yearMap.put("TRANSACTION_STATS_IN", 0d);
				yearMap.put("TRANSACTION_STATS_OUT", 0d);
			}
			if(tr.getType()==Type.RENT||tr.getType()==Type.PURCHASE||tr.getType()==Type.SALARIES_PAYMENT||tr.getType()==Type.PURCHASE){
				yearMap.put("TRANSACTION_STATS_OUT", yearMap.get("TRANSACTION_STATS_OUT")+tr.getAmount());
			}else{
				yearMap.put("TRANSACTION_STATS_IN", yearMap.get("TRANSACTION_STATS_IN")+tr.getAmount());
			}
			yearMap.put("TRANSACTION_STATS_TOT", yearMap.get("TRANSACTION_STATS_IN")-yearMap.get("TRANSACTION_STATS_OUT"));
			stats.put(tr.getDate().get(Calendar.YEAR), yearMap);
		}
		return stats;		
	}
	public static ArrayList<Transaction> getAllTransaction() throws Exception{
		return TransactionWrapper.getAllTransaction(true);
	}
	public static Collection<Transaction> getWagesTransactions()throws Exception{
		return TransactionWrapper.getWagesTransactions();
	}
	public static void registerTransaction(Transaction transaction) throws Exception{
		Checks.checkTransaction(transaction);
		TransactionWrapper.insertTransaction(true, transaction);
	}
	

}
